package main

import "sync"

type AtomMap[k comparable, v any] struct {
	sync.RWMutex
	m map[k]v
}

func NewAtomMap[K comparable, v any]() *AtomMap[K, v] {
	return &AtomMap[K, v]{
		m: make(map[K]v),
	}
}

/*
*
通过k获取val
*/
func (a *AtomMap[K, v]) Get(k K) (v any, bool2 bool) {
	a.RLock()
	defer a.RUnlock()
	v, existed := a.m[k]
	return v, existed
}

/*
*
设置键值对
*/
func (a *AtomMap[K, v]) Set(k K, v v) {
	a.Lock()
	defer a.Unlock()
	a.m[k] = v
}

/*
*
通过k删除键值对
*/
func (a *AtomMap[K, v]) Delete(k K) {
	a.Lock()
	defer a.Unlock()
	delete(a.m, k)
}

// 获取map的长度
func (a *AtomMap[K, v]) Len() int {
	a.Lock()
	defer a.Unlock()
	return len(a.m)
}

func (a *AtomMap[K, v]) Each(f func(k K, v any) bool) {
	a.Lock()
	defer a.Unlock()

	for k, v := range a.m {
		if !f(k, v) {
			return
		}
	}
}
